//获取应用实例
const app = getApp();

Page({
  data: {
    canvasWi: '',
    canvasHe: '',
    phoboxW: '',
    phoboxH: '',
    bgcolor: 0,
    imgbl: '',
    klboxt: '',
    klboxl: '',
    canvasw: 2000,
    imginterval: 10,
    widimg: '',
    heimg: '',
    widthimg: '',
    heightimg: '',
    toimg: 0,
    leimg: 0,
    toimgs: 0,
    leimgs: 0,
    starclick: '',
    pax: '',
    pay: '',
    whlin: '',
    kaungw: 315, //框宽
    kaungh: 444, //框高
    imgsf: '', //图片加载到屏幕缩放比例
    julione: 0, //两指头第一次放上去的距离
    julitow: '', //两指头第二次放上去的距离
    Scale: '', //放大比例
    isColours: true,
    lvarr: [],
    livurl: '',
    pic: [],
    propic: '', //服务器下载下来到图片路径
    pics: '',
    r: 255,
    g: 255,
    b: 255,
    isShow: true,
    ispichw: 105 / 148,
    id: 2, //打印类型
    cicun: 5, //结婚照id
    chicun: '',
    phoboxl: '',
    phoboxt: '',
    imgstopl: '',
    imgstopt: '',
    imagewidth: 0, // 缩放后的宽
    imageheight: 0, // 缩放后的高
    // 组件所需的参数
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '黑白照片打印', //导航栏 中间的标题
    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20,
    pictrs: '' //canvas处理过后到图片路径
  },
  onLoad(options) {
    let that = this;
    console.log(options);
    let query = wx.createSelectorQuery()
    query.select('.phobox').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      console.log(res)
      let phoboxW = res[0].width; // 要截取打印图片的宽度
      let phoboxH = res[0].height; // 要截取打印图片的高度
      that.setData({
        phoboxW: phoboxW,
        phoboxH: phoboxH
      })
      console.log(that.data.phoboxl, that.data.phoboxt, that.data.phoboxW, that.data.phoboxH)
    })
  },
  onShow(options) {
    let that = this;
    // 获取当前小程序的页面栈
    let pages = getCurrentPages();
    // 数组中索引最大的页面--当前页面
    let currentPage = pages[pages.length - 1];
    // 打印出当前页面中的 options
    console.log(currentPage.options)
    that.setData({
      id: currentPage.options.id,
      cicun: currentPage.options.id
    })
    if (that.data.cicun == 1) {
      that.setData({
        kaungw: 350, //框宽
        kaungh: 490
      })
    } else if (that.data.cicun == 2) {
      that.setData({
        kaungw: 330,
        kaungh: 480
      })
    } else if (that.data.cicun == 3) {
      that.setData({
        kaungw: 350,
        kaungh: 490
      })
    } else if (that.data.cicun == 6) {
      that.setData({
        kaungw: 400,
        kaungh: 400
      })
    } else if (that.data.cicun == 7) {
      that.setData({
        kaungw: 400,
        kaungh: 400
      })
    } else if (that.data.cicun == 8) {
      that.setData({
        kaungw: 400 * 7 / 9,
        kaungh: 400
      })
    } else if (that.data.cicun == 12) {
      that.setData({
        kaungw: 210 * 1.5,
        kaungh: 297 * 1.5,
        chicun: '21.0*29.7cm'
      })
    } else if (that.data.cicun == 13) {
      that.setData({
        kaungw: 315,
        kaungh: 444,
        chicun: '10.5*14.8cm'
      })
    }
  },
  // 上传图片
  uploadImage: function () {
    let that = this;
    let pic = that.data.pic;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success: function (res) {
            console.log(res)
            that.setData({
              phoboxwill: res.width / res.height,
              widimg: 505,
              heimg: 505 / (res.width / res.height),
              widthimg: 505,
              heightimg: 505 / (res.width / res.height),
              originalScale: originalScale,
              whlin: res.width / res.height,
              imgww: res.width,
              imghh: res.height,
              pic: res.path
            })
            wx.createSelectorQuery().select('.phoimgs').boundingClientRect(function (rect) {
              //图片放到屏幕缩放比例
              let rewid = rect.width;
              that.setData({
                imgsf: that.data.imgww / rewid
              })
            }).exec()
          }
        })
        // tempFilePath可以作为img标签的src属性显示图片
        let imgSrc = res.tempFilePaths
        let originalScale = res.height / res.width
        console.log(pic)
        pic.push(imgSrc);
        if (pic.length == 1) {
          that.setData({
            isShow: false,
            pic: pic[0],
          })
        }
      }
    })

  },
  // 触摸
  abtp(e) {
    if (e.touches.length == 1) {
      this.setData({
        pax: e.touches[0].pageX,
        pay: e.touches[0].pageY
      })
    } else if (e.touches.length == 2) {
      let julx = Math.abs(e.touches[0].pageX - e.touches[1].pageX)
      let july = Math.abs(e.touches[0].pageY - e.touches[1].pageY)
      let julione = Math.sqrt(julx * julx + july * july)
      this.setData({
        julione: julione
      })
    }
  },
  // 上传到服务器
  unloadfwq(src) {
    let that = this;
    // 上传到服务器
    var key = Math.random().toString(36).substr(2); //生成一个随机字符串的文件名
    let url = app.globalData.URL + 'common/upload'
    wx.uploadFile({
      url: url,
      filePath: src,
      header: {
        "Content-Type": "multipart/form-data",
        'accept': 'application/json',
        'Authorization': getApp().globalData.token //若有token，此处换上你的token，没有的话省略
      },
      name: 'file',
      formData: {
        'key': key //这里是为文件设置上传后的文件名
      },
      success: function (res) {
        console.log(res)
        let lvarr = JSON.parse(res.data)
        that.setData({
          lvarr: lvarr,
          livurl: lvarr.url,
          propic: lvarr.url,
        })

        console.log(lvarr, lvarr.url)
        let livurl = lvarr.url;
      },
      fail: function (res) { }
    })
  },

  // 监听手指移动时间
  seletime(e) {
    // 图片移动
    if (e.touches.length == 1) {
      let liveX = this.data.pax - e.touches[0].pageX
      let liveY = this.data.pay - e.touches[0].pageY
      this.setData({
        toimg: this.data.toimgs - liveY,
        leimg: this.data.leimgs - liveX
      })

    } else if (e.touches.length == 2) {

      let liveX = Math.abs(e.touches[1].pageX - e.touches[0].pageX)
      let liveY = Math.abs(e.touches[1].pageY - e.touches[0].pageY)
      let julitow = Math.sqrt(liveX * liveX + liveY * liveY)
      let sjuli = julitow - this.data.julione
      //  图片放大
      this.setData({
        widimg: this.data.widthimg + sjuli,
        heimg: (this.data.widthimg + sjuli) / this.data.whlin,
      })
    }
  },
  // 图片操作结束回调
  endimg(e) {
    let that = this;
    that.setData({
      toimgs: that.data.toimg,
      leimgs: that.data.leimg,
      widthimg: that.data.widimg,
      heightimg: that.data.heimg
    })

  },


  // 换底色
  item_change: function (e) {
    let that = this;
    if (that.data.pic == '') {
      wx.showToast({
        title: '请先选择照片',
        icon: 'none',
        duration: 2000
      })
    } else {
      //将框里的图片截取出来
      wx.showLoading({
        title: '处理中。。',
      })
      let src = that.data.pic;
      that.unloadfwq(src)

      setTimeout(function () {
        // 选择底色
        let type = e.currentTarget.id;
        let r = that.data.r;
        let g = that.data.g;
        let b = that.data.b;
        let picc = that.data.propic;
        if (type == 0) {
          that.setData({
            r: 255,
            g: 255,
            b: 255,
            bgcolor: e.currentTarget.id
          })
          that.gotophoto()
        } else if (type == 1) {
          that.setData({
            r: 255,
            g: 0,
            b: 0,
            bgcolor: e.currentTarget.id
          })
          that.gotophoto()
        } else if (type == 2) {
          that.setData({
            r: 0,
            g: 0,
            b: 255,
            bgcolor: e.currentTarget.id
          })
          that.gotophoto()
        } else if (type == 3) {
          that.setData({
            r: 255,
            g: 0,
            b: 0,
            bgcolor: e.currentTarget.id
          })
          that.gotophoto()
        }


      }, 2000);
    }


  },
  // 处理图片背景改变
  gotophoto: function () {
    let that = this;
    let r = that.data.r;
    let g = that.data.g;
    let b = that.data.b;
    let url = app.globalData.URL + 'facility/printOrder/imgSet';
    let data = {
      path: that.data.propic,
      r: r,
      g: g,
      b: b
    };
    app.wxRequest('GET', url, data, (res) => {
      wx.hideLoading();
      if (res.code != 200) {
        wx.showToast({
          title: 'err.errMsg',
          icon: 'none'
        })
        return
      }
      that.setData({
        propic: res.msg,
        pictrs: res.msg,
        pic: res.msg
      })
      wx.getImageInfo({
        src: that.data.propic,
        success: function (res) {
          console.log(res)
          that.setData({
            pic: res.path
          })
          console.log(that.data.pic)
        }
      })
    }, (err) => {
      console.log(err.errMsg)
      if (res.code != 200) {
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
        return
      }
    })

  },
  // 去打印
  gopicplace_order: function () {
    let that = this;
    if (that.data.pic == '') {
      wx.showToast({
        title: '请先选择照片',
        icon: 'none',
        duration: 2000
      })
      return false;
    }

    const widimg = that.data.widimg;
    const heimg = that.data.heimg;

    const kaungw = that.data.kaungw;
    const kaungh = that.data.kaungh;

    const toimg = that.data.toimg;
    const leimg = that.data.leimg;

    let imgww = that.data.imgww;
    let imghh = that.data.imghh;

    let phoboxwill = imgww / widimg;

    let canvswidth = kaungw * phoboxwill; //画布宽度
    let canvsheight = kaungh * phoboxwill; //画布高度
    that.setData({
      canvasHe: that.data.canvsheight,
      canvasWi: that.data.canvswidth
    })
    const ctx1 = wx.createCanvasContext('shareCanvas')
    let bgurl;
    if (that.data.bgcolor == 1) {
      bgurl = '../../../images/picture/bgblack.png'
    } else {
      bgurl = '../../../images/picture/bgA4.png'
    }
    ctx1.fillRect(0, 0, canvswidth, canvsheight);
    ctx1.setFillStyle("#fff");
    ctx1.drawImage(bgurl, 0, 0, canvswidth, canvsheight); //绘制图片
    ctx1.drawImage(that.data.pic, that.data.leimg * phoboxwill, that.data.toimg * phoboxwill, imgww, imghh); //绘制图片

    //保存生成的单张图片
    ctx1.draw(false, function () {
      setTimeout(function () {
        wx.canvasToTempFilePath({ //把当前画布指定区域的内容导出生成指定大小的图片，并返回文件路径
          x: 0,
          y: 0,
          width: canvswidth,
          height: canvsheight,
          canvasId: 'shareCanvas',
          fileType: 'jpg',
          success: function (res) {
            wx.hideLoading();
            // wx.saveImageToPhotosAlbum({
            //   filePath: res.tempFilePath,
            // })
            wx.navigateTo({
              url: '/modelA/pages/drawings_printing/picplace_order/picplace_order?pics=' + res.tempFilePath + '&title=' + that.data.nvabarData.title + '&ccinfo=' + that.data.chicun + '&type=' + that.data.type + '&isColours=' + that.data.isColours + '&id=' + that.data.id,
            })
          },
        })
      }, 300)
    });

    // let that = this;
    // if (that.data.pic == '') {
    //   wx.showToast({
    //     title: '请先选择照片',
    //     icon: 'none',
    //     duration: 2000
    //   })
    // } else {
    //   wx.showLoading({
    //     title: '正在生成订单。。。',
    //   })
    //   let rpx;
    //   // 获取不同手机屏幕自适应
    //   wx.getSystemInfo({
    //     complete: (res) => {
    //       rpx = res.windowWidth / 414;
    //       console.log('windowWidth', res.windowWidth);
    //     },
    //   })
    //   console.log('rpx', rpx);
    //   console.log('leimg', that.data.leimg);
    //   console.log('toimg', that.data.toimg);
    //   //将框里的图片截取出来
    //   let phoboxwill = that.data.imgsf * rpx; //图片缩放比例
    //   let canvswidth = that.data.imgww + that.data.leimg * phoboxwill; //画布宽度
    //   let canvsheight = that.data.imghh + that.data.toimg * phoboxwill; //画布高度
    //   let imgww = that.data.imgww;
    //   let imghh = that.data.imghh;
    //   console.log(canvswidth, canvsheight)
    //   const ctx1 = wx.createCanvasContext('shareCanvas')
    //   that.setData({
    //     canvasHe: that.data.canvsheight,
    //     canvasWi: that.data.canvswidth
    //   })
    //   let bgurl;
    //   if (that.data.bgcolor == 1) {
    //     bgurl = '../../../images/picture/bgblack.png'
    //   } else {
    //     bgurl = '../../../images/picture/bgA4.png'
    //   }
    //   ctx1.fillRect(0, 0, canvswidth, canvsheight);
    //   ctx1.setFillStyle("#fff");
    //   ctx1.drawImage(bgurl, 0, 0, canvswidth, canvsheight); //绘制图片

    //   console.log(imgww, imghh, phoboxwill, that.data.leimg, that.data.toimg);

    //   // ctx1.drawImage(that.data.pic, that.data.leimg * phoboxwill / 2, that.data.toimg * phoboxwill / 2, imgww, imghh); //绘制图片

    //   console.log
    //   //保存生成的单张图片
    //   ctx1.draw(false, function () {
    //     setTimeout(function () {
    //       wx.canvasToTempFilePath({ //把当前画布指定区域的内容导出生成指定大小的图片，并返回文件路径
    //         x: 0,
    //         y: 0,
    //         width: that.data.phoboxW * phoboxwill,
    //         height: that.data.phoboxW * phoboxwill * that.data.kaungh / that.data.kaungw,
    //         canvasId: 'shareCanvas',
    //         fileType: 'jpg',
    //         success: function (res) {
    //           wx.hideLoading();
    //           wx.saveImageToPhotosAlbum({
    //             filePath: res.tempFilePath,
    //           })
    //           // wx.navigateTo({
    //           //   url: '/modelA/pages/drawings_printing/picplace_order/picplace_order?pics=' + res.tempFilePath + '&title=' + that.data.nvabarData.title + '&ccinfo=' + that.data.chicun + '&type=' + that.data.type + '&isColours=' + that.data.isColours + '&id=' + that.data.id,
    //           // })
    //         },
    //       })
    //     }, 300)
    //   });

    // }

  }
})